package com.liu;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * @author LIU
 * @version 1.0.0
 * @date 2025/10/26
 */
public class RestTemplateThatTrustsAll {
    public static void main(String[] args) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
//        RestTemplate restTemplate = getRestTemplateThatTrustsAll();
        JSONObject params = new JSONObject();
        JSONObject forObject = restTemplate.postForObject("https://deo.aidrilling.com:1002/rxd-service/well-site/construction",params, JSONObject.class);
        System.out.println(forObject);
    }


    public static RestTemplate getRestTemplateThatTrustsAll() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        // 1. 定义信任所有证书的策略
        TrustStrategy acceptingTrustStrategy = (chain, authType) -> true;

        // 2. 创建 SSLContext
        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy)
                .build();

        // 3. 创建 SSL Socket Factory，并跳过主机名验证
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext,
                NoopHostnameVerifier.INSTANCE); // 注意：这个类在 org.apache.http.conn.ssl 包下

        // 4. 创建 HttpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build();

        // 5. 创建 RequestFactory 并设置给 RestTemplate
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);

        return new RestTemplate(requestFactory);
    }
}
